﻿using DiLe.Mes.Application.Common;
using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Application.Common.Mould;
using DiLe.Mes.Application.Common.Mould.ViewModel;
using DiLe.Mes.Model.Common.Mould.Entity.Info;
using DiLe.Mes.Model.Common.Mould.Entity.Maintenance;
using DiLe.Mes.Model.Common.Mould.Entity.Repair;
using DiLe.Mes.Model.Common.Mould.Entity.SparePart;
using DiLe.Mes.Model.Common.System.Entity;
using Mapster;

namespace DiLe.Mes.Application.Handler
{
    /// <summary>
    /// 
    /// </summary>
    public class MouldExjosnHandler {
        private readonly MouldInfoClient _mouldInfoClient;
        private readonly MouldSparePartClient _mouldSparePartClient;
        private readonly MouldRepairClient _mouldRepairClient;
        private readonly MouldMaintenanceClient _mouldMaintenanceClient;

        private readonly SystemClient _systemClient;
        private readonly OrganizationClient _organizationClient;
        private readonly EquipmentManageClient _equipmentManageClient;
        /// <summary>
        /// 构造函数
        /// </summary>
        public MouldExjosnHandler(MouldInfoClient mouldInfoClient,
                                  MouldSparePartClient mouldSparePartClient,
                                  MouldRepairClient mouldRepairClient,
                                  SystemClient systemClient,
                                  EquipmentManageClient equipmentManageClient,
                                 OrganizationClient organizationClient,
                                 MouldMaintenanceClient mouldMaintenanceClient) {
            _mouldInfoClient = mouldInfoClient;
            _mouldSparePartClient = mouldSparePartClient;
            _mouldRepairClient = mouldRepairClient;
            _systemClient = systemClient;
            _equipmentManageClient = equipmentManageClient;
            _organizationClient = organizationClient;
            _mouldMaintenanceClient = mouldMaintenanceClient;
        }
        #region info
        /// <summary>
        /// 填充模具档案的额外字段
        /// </summary>
        /// <returns></returns>
        public async Task FillMouldInfoExjosn(List<MouldInfoEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            //模具类型
            var typeIds = dataList.Select(p => p.TypeId).Distinct().ToList();
            var typeList = await _mouldInfoClient.GetMouldTypeListAsync(p => typeIds.Contains(p.Id));
            //模具状态
            var statusIds = dataList.Select(p => p.StatusId).Distinct().ToList();
            var statusList = await _mouldInfoClient.GetMouldStatusListAsync(p => statusIds.Contains(p.Id));
            //位置
            var positionIds = dataList.Select(p => p.PositionId).Distinct().ToList();
            var positionList = await _systemClient.GetPositionListAsync(p => positionIds.Contains(p.Id));
            //工厂
            var factoryIds = dataList.Where(x => x.FactoryId != null).Select(p => p.FactoryId).Distinct().ToList();
            var factoryList = await _organizationClient.GetOrganizationListAsync(p => factoryIds.Contains(p.Id));

            //设备类型
            var equipmentTypeIds = dataList.Select(p => p.EquipmentTypeId).Distinct().ToList();
            var equipmentTypeList = await _equipmentManageClient.GetEquipmentTypeListAsync(p => equipmentTypeIds.Contains(p.Id));
            //负责人
            var userList = await _organizationClient.GetUserListAsync();


            foreach (var item in dataList) {

                var type = typeList?.FirstOrDefault(p => p.Id == item.TypeId);
                item.ExtJson.Add("TypeName", type?.Name);

                var status = statusList?.FirstOrDefault(p => p.Id == item.StatusId);
                item.ExtJson.Add("StatusName", status?.Name);

                var position = positionList?.FirstOrDefault(p => p.Id == item.PositionId);
                item.ExtJson.Add("PositionName", position?.Position);

                var equipmentType = equipmentTypeList?.FirstOrDefault(p => p.Id == item.EquipmentTypeId);
                item.ExtJson.Add("EquipmentTypeName", equipmentType?.Name);

                var user = userList?.FirstOrDefault(p => p.Id == item.Manager);
                item.ExtJson.Add("ManagerName", user?.Name);

                var oper = userList?.FirstOrDefault(p => p.Id == item.Operator);
                item.ExtJson.Add("OperatorName", oper?.Name);

                var factory = factoryList?.FirstOrDefault(p => p.Id == item.FactoryId);
                item.ExtJson.Add("FactoryName", factory?.Name);
            }
        }


        /// <summary>
        /// 填充模具类型的额外字段
        /// </summary>
        /// <returns></returns>
        public async Task FillMouldTypeExjosn(List<MouldTypeEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            //父级
            var parentIds = dataList.Select(p => p.ParentId).Distinct().ToList();
            var parentList = await _mouldInfoClient.GetMouldTypeListAsync(p => parentIds.Contains(p.Id));
            foreach (var item in dataList) {
                var parent = parentList?.FirstOrDefault(p => p.Id == item.ParentId);
                item.ExtJson.Add("ParentName", parent?.Name);
            }
        }
        #endregion

        #region Repair

        /// <summary>
        /// 填充故障类型的额外字段
        /// </summary>
        /// <returns></returns>
        public async Task FillMouldRepairTypeExjosn(List<MouldRepairTypeEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            //父级
            var parentIds = dataList.Select(p => p.ParentId).Distinct().ToList();
            var parentList = await _mouldRepairClient.GetMouldRepairTypeListAsync(p => parentIds.Contains(p.Id));
            foreach (var item in dataList) {
                var parent = parentList?.FirstOrDefault(p => p.Id == item.ParentId);
                item.ExtJson.Add("ParentName", parent?.Name);
            }
        }
        /// <summary>
        /// 获取保养记录视图模型列表
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task<List<MouldRepairRecordDto>> GetMouldRepairRecordDto(List<MouldRepairRecordEntity> dataList) {
            var list = new List<MouldRepairRecordDto>();
            if (dataList.Count == 0) {
                return list;
            }
            await FillMouldRepairRecordExjosn(dataList);
            //设备
            var mouldIds = dataList.Select(p => p.MouldId).Distinct().ToList();
            var mouldList = await _mouldInfoClient.GetMouldInfoListAsync(p => mouldIds.Contains(p.Id));
            await FillMouldInfoExjosn(mouldList);

            foreach (var item in dataList) {
                var dto = new MouldRepairRecordDto();
                dto.Model = item;
                dto.EquipmentModel = mouldList?.FirstOrDefault(p => p.Id == item.MouldId) ?? new MouldInfoEntity();
                list.Add(dto);
            }
            return list;
        }
        /// <summary>
        /// 填充维修记录的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillMouldRepairRecordExjosn(List<MouldRepairRecordEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            var userList = await _organizationClient.GetUserListAsync();
            //故障类型
            var faultTypeIds = dataList.Select(p => p.FaultType).Distinct().ToList();
            var faultTypeList = await _mouldRepairClient.GetMouldRepairTypeListAsync(p => faultTypeIds.Contains(p.Id));
            //班组
            var teamIds = dataList.Select(p => p.TeamId).Distinct().ToList();
            var teamList = await _systemClient.GetTeamListAsync(p => teamIds.Contains(p.Id));
            //仓库
            var warehouseIds = dataList.Select(p => p.WarehouseId).Distinct().ToList();
            var warehouseList = await _systemClient.GetWarehouseListAsync(p => warehouseIds.Contains(p.Id));
            foreach (var item in dataList) {
                var team = teamList?.FirstOrDefault(p => p.Id == item.TeamId);
                item.ExtJson.Add("TeamName", team?.Name);

                var faultType = faultTypeList?.FirstOrDefault(p => p.Id == item.FaultType);
                item.ExtJson.Add("FaultTypeName", faultType?.Name);

                var manager = userList?.FirstOrDefault(p => p.Id == item.Manager);
                item.ExtJson.Add("ManagerName", manager?.Name);

                var warehouse = warehouseList?.FirstOrDefault(p => p.Id == item.WarehouseId);
                item.ExtJson.Add("WarehouseName", warehouse?.Name);

                var users = userList?.Where(p => item.PersonnelList.Contains(p.Id)).ToList();
                if (!users.None()) {
                    item.ExtJson.Add("PersonnelNames", string.Join(",", users!.ConvertAll(p => p.Name)));
                }

            }
        }
        #endregion
        #region SparePart
        /// <summary>
        /// 填充模具备件的额外字段
        /// </summary>
        /// <returns></returns>
        public async Task<List<MouldSparePartLedgerModel>> FillMouldSparePartLedgerExjosn(List<MouldSparePartLedgerEntity> dataList) {
            var list = new List<MouldSparePartLedgerModel>();
            if (!dataList.None()) {
                return list;
            }
            //模具类型
            var typeIds = dataList.Select(p => p.TypeId).Distinct().ToList();
            var typeList = await _mouldSparePartClient.GetMouldSparePartTypeListAsync(p => typeIds.Contains(p.Id));
            //单位
            var unitIds = dataList.Select(p => p.Unit).Distinct().ToList();
            var unitList = await _systemClient.GetMeasureUnitListAsync(p => unitIds.Contains(p.Id));
            //库存
            var inventoryIds = dataList.ConvertAll(p => p.Id);
            var inventoryList = await _systemClient.GetSparePartInventoryListAsync(x => inventoryIds.Contains(x.SparePartId));

            foreach (var data in dataList) {
                var item = data.Adapt<MouldSparePartLedgerModel>();
                var type = typeList?.FirstOrDefault(p => p.Id == item.TypeId);
                item.ExtJson.Add("TypeName", type?.Name);
                var unit = unitList?.FirstOrDefault(p => p.Id == item.Unit);
                item.ExtJson.Add("UnitName", unit?.Name);
                var inventory = inventoryList?.FirstOrDefault(p => p.SparePartId == item.Id);
                item.InventoryTotalLimit = inventory?.InventoryQuantity ?? 0;
                list.Add(item);
            }
            return list;
        }

        /// <summary>
        /// 填充备件台账的额外字段
        /// </summary>
        /// <param name="data"></param>
        public async Task<MouldSparePartLedgerModel> FillMouldSparePartLedgerExjosn(MouldSparePartLedgerEntity data) {
            MouldSparePartLedgerModel result = new();
            if (data == null) {
                return result;
            }
            //类型
            var type = await _mouldSparePartClient.GetMouldSparePartTypeInfoAsync(data.TypeId);
            //单位
            var unit = await _systemClient.GetMeasureUnitInfoAsync(data.Unit);
            //库存
            var inventory = await _systemClient.GetSparePartInventoryAsync(x => x.SparePartId == data.Id);

            result = data.Adapt<MouldSparePartLedgerModel>();
            result.ExtJson.Add("TypeName", type?.Name);
            result.ExtJson.Add("UnitName", unit?.Name);
            result.InventoryTotalLimit = inventory?.InventoryQuantity ?? 0;
            return result;
        }



        /// <summary>
        /// 填充备件类型的额外字段
        /// </summary>
        /// <returns></returns>
        public async Task FillMouldSparePartTypeExjosn(List<MouldSparePartTypeEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            //父级
            var parentIds = dataList.Select(p => p.ParentId).Distinct().ToList();
            var parentList = await _mouldSparePartClient.GetMouldSparePartTypeListAsync(p => parentIds.Contains(p.Id));
            foreach (var item in dataList) {
                var parent = parentList?.FirstOrDefault(p => p.Id == item.ParentId);
                item.ExtJson.Add("ParentName", parent?.Name);
            }
        }
        /// <summary>
        /// 填充备件入库的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillMouldSparePartStockInExjosn(List<MouldSparePartStockInEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            //仓库
            var warehouseIds = dataList.Select(p => p.WarehouseId).Distinct().ToList();
            var warehouseList = await _systemClient.GetWarehouseListAsync(p => warehouseIds.Contains(p.Id));
            //用户
            var useIds = warehouseList?.ConvertAll(p => p.Manager) ?? new List<long>();
            var userList = await _organizationClient.GetUserListAsync(p => useIds.Contains(p.Id));

            foreach (var item in dataList) {
                var warehouse = warehouseList?.FirstOrDefault(p => p.Id == item.WarehouseId);
                item.ExtJson.Add("WarehouseName", warehouse?.Name);
                var user = userList?.FirstOrDefault(p => p.Id == warehouse?.Manager);
                item.ExtJson.Add("WarehouseManagerName", user?.Name);
            }
        }

        /// <summary>
        /// 填充备件出库的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillMouldSparePartStockOutExjosn(List<MouldSparePartStockOutEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            //负责人
            var userList = await _organizationClient.GetUserListAsync();
            //部门
            var departmentList = await _organizationClient.GetOrganizationListAsync();
            //仓库
            var warehouseIds = dataList.Select(p => p.WarehouseId).Distinct().ToList();
            var warehouseList = await _systemClient.GetWarehouseListAsync(p => warehouseIds.Contains(p.Id));
            //出库关联
            var ids = dataList.ConvertAll(p => p.Id);
            var rels = await _mouldSparePartClient.GetMouldStockOut2SparePartListAsync(p => ids.Contains(p.StockOutId));

            foreach (var item in dataList) {
                var warehouse = warehouseList?.FirstOrDefault(p => p.Id == item.WarehouseId);
                item.ExtJson.Add("WarehouseName", warehouse?.Name);

                var warehouseManager = userList?.FirstOrDefault(p => p.Id == warehouse?.Manager);
                item.ExtJson.Add("WarehouseManagerName", warehouseManager?.Name);
                //申请人
                var applicant = userList?.FirstOrDefault(p => p.Id == item.Applicant);
                item.ExtJson.Add("ApplicantName", applicant?.Name);
                //所在部门  
                var applicantdepartment = departmentList?.FirstOrDefault(p => p.Id == applicant?.DepartmentId);
                item.ExtJson.Add("ApplicantDepartmentName", applicantdepartment?.Name);
                //出库人员
                var stockoutuser = userList?.FirstOrDefault(p => p.Id == item.StockOutUserId);
                item.ExtJson.Add("StockOutUserName", stockoutuser?.Name);

                //出库数量
                var stockoutnumber = rels?.Where(p => p.StockOutId == item.Id).Sum(p => p.StockOutNumber);
                item.ExtJson.Add("StockOutUserNum", stockoutnumber);
            }
        }
        #endregion

        #region Maintenance
        /// <summary>
        /// 获取保养计划视图模型列表
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task<List<MouldMaintenancePlanDto>> GetMouldMaintenancePlanDto(List<MouldMaintenancePlanEntity> dataList) {
            var list = new List<MouldMaintenancePlanDto>();
            if (!dataList.None()) {
                return list;
            }
            await FillMouldMaintenancePlanExjosn(dataList);
            //模具
            var mouldIds = dataList.Select(p => p.MouldId).Distinct().ToList();
            var mouldList = await _mouldInfoClient.GetMouldInfoListAsync(p => mouldIds.Contains(p.Id));
            await FillMouldInfoExjosn(mouldList);
            //规则
            var executeRuleIds = dataList.Select(p => p.ExecuteRuleId).Distinct().ToList();
            var executeRuleList = await _systemClient.GetExecuteRuleListAsync(p => executeRuleIds.Contains(p.Id));
            foreach (var item in dataList) {
                var dto = new MouldMaintenancePlanDto();
                dto.Model = item;
                dto.MouldModel = mouldList.FirstOrDefault(p => p.Id == item.MouldId) ?? new MouldInfoEntity();
                dto.ExecuteRuleModel = executeRuleList.FirstOrDefault(p => p.Id == item.ExecuteRuleId) ?? new ExecuteRuleEntity();
                list.Add(dto);
            }
            return list;
        }
        /// <summary>
        /// 填充保养计划的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task FillMouldMaintenancePlanExjosn(List<MouldMaintenancePlanEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            var userList = await _organizationClient.GetUserListAsync();
            //班组
            var teamIds = dataList.Select(p => p.TeamId).Distinct().ToList();
            var teamList = await _systemClient.GetTeamListAsync(p => teamIds.Contains(p.Id));
            //规则
            var executeRuleIds = dataList.Select(p => p.ExecuteRuleId).Distinct().ToList();
            var executeRuleList = await _systemClient.GetExecuteRuleListAsync(p => executeRuleIds.Contains(p.Id));

            foreach (var item in dataList) {
                var manager = userList?.FirstOrDefault(p => p.Id == item.Manager);
                item.ExtJson.Add("ManagerName", manager?.Name);

                var team = teamList?.FirstOrDefault(p => p.Id == item.TeamId);
                item.ExtJson.Add("TeamName", team?.Name);

                var users = userList?.Where(p => item.OtherUserIds.Contains(p.Id)).ToList();
                if (!users.None()) {
                    item.ExtJson.Add("OtherPeopleName", string.Join(",", users!.ConvertAll(p => p.Name)));
                }
                var executeRule = executeRuleList?.FirstOrDefault(p => p.Id == item.ExecuteRuleId);
                item.ExtJson.Add("ExecuteRuleName", executeRule?.Name);
                item.ExtJson.Add("ExecuteRuleDescription", executeRule?.RuleDescription);
            }
        }
        /// <summary>
        /// 填充保养项目的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task FillMouldMaintenanceProjectExjosn(List<MouldMaintenanceProjectEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            //保养类型
            var maintenanceTypeIds = dataList.Select(p => p.MaintenanceType).Distinct().ToList();
            var maintenanceTypeList = await _mouldSparePartClient.GetMouldSparePartTypeListAsync(p => maintenanceTypeIds.Contains(p.Id));
            //保养级别
            var maintenanceLevelIds = dataList.Select(p => p.MaintenanceLevel).Distinct().ToList();
            var maintenanceLevelList = await _systemClient.GetMaintenanceLevelListAsync(p => maintenanceLevelIds.Contains(p.Id));

            foreach (var item in dataList) {
                var maintenanceType = maintenanceTypeList?.FirstOrDefault(p => p.Id == item.MaintenanceType);
                item.ExtJson.Add("MaintenanceTypeName", maintenanceType?.Name);

                var maintenanceLevel = maintenanceLevelList?.FirstOrDefault(p => p.Id == item.MaintenanceLevel);
                item.ExtJson.Add("MaintenanceLevelName", maintenanceLevel?.Name);
            }
        }
        /// <summary>
        /// 获取保养记录视图模型列表
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task<List<MouldMaintenanceRecordDto>> GetMouldMaintenanceRecordDto(List<MouldMaintenanceRecordEntity> dataList) {
            var list = new List<MouldMaintenanceRecordDto>();
            if (!dataList.None()) {
                return list;
            }
            var userList = await _organizationClient.GetUserListAsync();
            //计划
            var planIds = dataList.Select(p => p.MaintenancePlanId).Distinct().ToList();
            var planList = await _mouldMaintenanceClient.GetMouldMaintenancePlanListAsync(p => planIds.Contains(p.Id));
            await FillMouldMaintenancePlanExjosn(planList);
            //模具
            var mouldIds = dataList.Select(p => p.MouldId).Distinct().ToList();
            var mouldList = await _mouldInfoClient.GetMouldInfoListAsync(p => mouldIds.Contains(p.Id));
            await FillMouldInfoExjosn(mouldList);

            foreach (var item in dataList) {
                var dto = new MouldMaintenanceRecordDto();
                dto.Model = item;
                dto.PlanModel = planList?.FirstOrDefault(p => p.Id == item.MaintenancePlanId) ?? new MouldMaintenancePlanEntity();
                dto.MouldModel = mouldList?.FirstOrDefault(p => p.Id == item.MouldId) ?? new MouldInfoEntity();
                list.Add(dto);
            }
            return list;
        }
        /// <summary>
        /// 填充保养记录的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task FillMouldMaintenanceRecordExjosn(List<MouldMaintenanceRecordEntity> dataList) {
            if (!dataList.None()) {
                return;
            }
            var userList = await _organizationClient.GetUserListAsync();
            //仓库
            var warehouseIds = dataList.Select(p => p.WarehouseId).Distinct().ToList();
            var warehouseList = await _systemClient.GetWarehouseListAsync(p => warehouseIds.Contains(p.Id));

            foreach (var item in dataList) {
                var warehouse = warehouseList?.FirstOrDefault(p => p.Id == item.WarehouseId);
                item.ExtJson.Add("WarehouseName", warehouse?.Name);
            }

        }
        #endregion
    }
}
